package com.dkm.ec.home.domain;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.dkm.base.core.helper.SpringHelper;
import com.dkm.base.core.util.BeanUtils;
import com.dkm.biz.domain.AbstractDomain;
import com.dkm.biz.gl.domain.EavAttribute;
import com.dkm.biz.gl.domain.GlText;
import com.dkm.biz.gl.persistence.dao.GlCateQueryDao;
import com.dkm.biz.gl.persistence.dao.GlTextDao;
import com.dkm.biz.gl.persistence.entity.AttrRangPo;
import com.dkm.biz.gl.persistence.entity.GlCatePo;
import com.dkm.biz.gl.repository.GlTextRepository;
import com.dkm.biz.gl.service.EavAttrService;
import com.dkm.biz.gl.util.AttrRangeUtil;
import com.dkm.ec.home.persistence.dao.HomeEntityDao;
import com.dkm.ec.home.persistence.entity.HomeEntityPo;
import com.dkm.ec.home.repository.HomeEntityRepository;
import com.dkm.ec.product.domain.ProdRel;
import com.dkm.ec.product.domain.ProdSeo;
import com.dkm.ec.product.domain.ProductEntity;
import com.dkm.ec.product.domain.ProductMedia;
import com.dkm.ec.product.persistence.dao.ProdRelDao;
import com.dkm.ec.product.persistence.dao.ProdSeoDao;
import com.dkm.ec.product.persistence.dao.ProductEntityDao;
import com.dkm.ec.product.persistence.dao.ProductMediaDao;
import com.dkm.ec.product.persistence.entity.ProdRelPo;
import com.dkm.ec.product.persistence.entity.ProdSeoPo;
import com.dkm.ec.product.persistence.entity.ProductEntityPo;
import com.dkm.ec.product.persistence.entity.ProductMediaPo;
import com.dkm.ec.product.repository.ProdSeoRepository;
import com.dkm.ec.product.repository.ProductEntityRepository;
import com.dkm.ec.product.repository.ProductMediaRepository;
import com.dkm.ec.product.service.ProductMediaService;

/**
 * 对象功能:家居产品 领域对象实体
 * 开发公司:SKG.COM
 * 开发人员:颜超敏
 * 创建时间:2014-12-17 11:31:17
 */
@Service
@Scope("prototype")
public class HomeEntity extends AbstractDomain<String, HomeEntityPo>{
	 private HomeEntityDao homeEntityDao = null;
	
	 private ProductEntityRepository productEntityRepository;
	 
	 private ProductMediaRepository productMediaRepository;
	 @Resource
	 private GlTextRepository glTextRepository;
	 @Resource
	 private ProdSeoRepository  prodSeoRepository;
	 @Resource
	 private HomeEntityRepository homeEntityRepository;
	@Resource 
	private EavAttribute eavAttribute;
	@Resource 
	private ProductMedia productMedia;
	@Resource
	private ProductMediaService productMediaService;
	@Resource
	private GlTextDao glTextDao;
	 @Resource
	 private ProductMediaDao  productMediaDao;
	 @Resource
	 private ProdSeoDao prodSeoDao;
	@Resource
	 private GlCateQueryDao glCateQueryDao;
	 
	 @Resource
	 private ProdRel prodRel;
	 @Resource
	 private ProdRelDao prodRelDao;
	 @Resource
	 private ProductEntityDao productEntityDao;
	 @Resource
	 EavAttrService eavAttrService;
	 
	 

	protected void init(){
		homeEntityDao = SpringHelper.getBean(HomeEntityDao.class);
		productEntityRepository = SpringHelper.getBean(ProductEntityRepository.class);
		productMediaRepository = SpringHelper.getBean(ProductMediaRepository.class);
		setDao(homeEntityDao);
	}	 
	
	/**
	 * 保存【家居产品】
	 * @param 
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public void saveHomeEntity() throws ParseException {
		
		boolean isNew = StringUtils.isEmpty(getData().getHomeId())?true:false;
		ProductEntity productEntity = new ProductEntity();
		ProductEntityPo  productEntityPo = null;
		if(!isNew){
			 productEntity = productEntityRepository.load(getData().getHomeId());
		}else{
			 productEntity = productEntityRepository.newInstance();		
		}
		productEntityPo = productEntity.getData();
	
	
        //保存详细内容		
		String descContent=getData().getDescContent();
		if(StringUtils.isNotEmpty(getData().getDescFid())){
			GlText glText = glTextRepository.load(getData().getDescFid());
		//	glText.saveText(descContent);
		}else{
			GlText glText = glTextRepository.newInstance();
		//	String descFid=glText.saveText(descContent);
			//getData().setDescFid(descFid);
		}	
		
		//保存产品
		
		try {
			BeanUtils.copyProperties(productEntityPo, getData());	
			if(!isNew){
				productEntityPo.setId(getData().getHomeId() );
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		

		productEntity.setData(productEntityPo);
		productEntity.save();	
		if(isNew){
			getData().setHomeId(productEntity.getId());
			getData().setId(productEntity.getId());
			setNewFlag(true);
		}
		
		//保存属性值
		eavAttribute.saveAttrValue(getData().getAttrDataMap(),productEntity.getId(),getData().getEavSetKey());
		
		//保存seo
		ProdSeoPo prodSeoPo = getData().getProdSeoPo();
		if(prodSeoPo!=null && StringUtils.isNotEmpty(prodSeoPo.getId())){
			prodSeoDao.update(prodSeoPo);
		}else{
			ProdSeo prodSeo = prodSeoRepository.load(productEntity.getId());
			if(prodSeo!=null&&prodSeo.getData()!=null){
				try {
					prodSeoPo.setId(prodSeo.getData().getId());
					} catch (Exception e) {
					e.printStackTrace();
				}					
				prodSeoDao.update(prodSeoPo);
			}else{
				if(prodSeoPo==null)prodSeoPo = new ProdSeoPo();
				prodSeoPo.setId(productEntity.getId());
				prodSeoDao.create(prodSeoPo);
			}
		}	
		
		//保存效果图
		String homeMediaId =productMedia.saveMedias(getData().getProductMediaPos(), productEntity.getId(),"deleteByProdId");

		getData().setHomeMediaId(homeMediaId);
		super.save();
		
		//保存户型与场景的关联关系
		if(StringUtils.isNotEmpty(getData().getType())&&getData().getType().equals(HomeEntityPo.TYPE.WHOLE)){
		//	prodRel.saveRelForWhole(getData().getProdReList(),productEntity.getId(),ProdRelPo.RELTYPE.HOMETYPESCENE);
		}
		if(getData().isNeedGenSolr()){
			loadStyleKeys();
			if(StringUtils.isNotEmpty(getData().getType())&&getData().getType().equals(HomeEntityPo.TYPE.WHOLE)){
				//solr AddOrUpdate
				if(isNew){
				//	HomeSolr.add(getHomeEntityPo(productEntity));
				}else{
					//HomeSolr.update(getHomeEntityPo(productEntity));
				}
			}
			else{
				//solr AddOrUpdate
				if(isNew){
					//ProdSolr.add(getHomeEntityPo(productEntity));
				}else{
					//ProdSolr.update(getHomeEntityPo(productEntity));
				}
			}
		}	
	}
	
	/**
	 * 删除【家居产品】
	 * @param id
	 * @param homeType
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public void destoryEntity(String id,String homeType){
				//delete attr
				eavAttribute.deleteAttrValueByEntityId(id);
				//delete seo
				prodSeoDao.delete(id);
				//delete Product Media
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("prodId", id);
				productMediaDao.deleteByKey("deleteByProdId", params);
				//delete rel
				if(StringUtils.isNotEmpty(homeType)){
					if(homeType.equals(HomeEntityPo.TYPE.SCENE)){
						prodRelDao.deleteByRelId(id);
					}
					else if(homeType.equals(HomeEntityPo.TYPE.WHOLE)){
						prodRelDao.deleteByMainId(id);
					}
				}
				//delete desc
				HomeEntity homeEntity = homeEntityRepository.load(id);
				if(homeEntity!=null&&homeEntity.getData()!=null&&homeEntity.getData().getDescFid()!=null){
					glTextDao.delete(homeEntity.getData().getDescFid());
				}
				//delete product
				productEntityDao.delete(id);
				//delete homeEntity
				super.destroy(id);
				//solr delete
			//	ProdSolr.delete(id);
	}		

		
	
	public void loadForDetail(){
		
        //查询详细内容		
		if(StringUtils.isNotEmpty(getData().getDescFid())){
			GlText glText = glTextRepository.load(getData().getDescFid());
			if(glText!=null){
				getData().setDescContent(glText.getData().getText());	
			}
		}
		if(StringUtils.isNotEmpty(getData().getMainCateId())){
			GlCatePo glCatePo = glCateQueryDao.get(getData().getMainCateId());
			getData().setCateName(glCatePo.getName());
			getData().setCateKey(glCatePo.getKey());
		}
		
		  //查询EntitySeo		
		if(StringUtils.isNotEmpty(getData().getId())){
			ProdSeo prodSeo = prodSeoRepository.load(getData().getId());
			if(prodSeo!=null){
				getData().setProdSeoPo(prodSeo.getData());		
			}
		
		}
	}
	
	public void loadStyleKeys(){
		if(StringUtils.isNotEmpty(getData().getStyleId())){
			GlCatePo glCatePo = glCateQueryDao.get(getData().getStyleId());
			getData().setStyleKey(glCatePo.getKey());
		}
		if(StringUtils.isNotEmpty(getData().getSubStyleId())){
			GlCatePo glCatePo = glCateQueryDao.get(getData().getSubStyleId());
			getData().setSubStyleKey(glCatePo.getKey());
		}
	}
	
	/**
	 * 加载属性值
	 * @param 
	 * @return 
	 */
	public void loadEavValues(){
		 Map<String, Object> attrDataMap =eavAttrService.getAttrValuesByProdSetKey(getId(),getData().getEavSetKey());
		getData().setAttrDataMap(attrDataMap);
	}
	
	/**
	 * 加载效果图
	 * @param 
	 * @return 
	 */
	public void loadEntityMedia(){
		if(StringUtils.isNotEmpty(getData().getHomeId())){
			
			List<ProductMediaPo> productMediaPos= productMediaRepository.findByProdId(getData().getHomeId());
			productMediaService.setCateKeys(productMediaPos);
			getData().setProductMediaPos(productMediaPos);
		}
	
	}


	/**
	 *户型加载场景
	 * @param 
	 * @return
	 */
	public void loadWholeHome() {
        //查询详细内容		
		if(StringUtils.isNotEmpty(getData().getHomeId())){
			
			List<HomeEntityPo> associatWholeHomeEntityPos=homeEntityRepository.findAssociatWholeHomeEntityPo(getData().getHomeId());
			List<HomeEntityPo> pos=new ArrayList<HomeEntityPo>();
			if(associatWholeHomeEntityPos!=null){
				for(HomeEntityPo po:associatWholeHomeEntityPos){
					po=homeEntityRepository.findDetailByKey(po.getKey());
					pos.add(po);
				}
			}
			getData().setAssociatWholeHomeEntityPos(pos);
		}				
	}
	
	public void loadSolrValues(){
		Map<String, Object> attrDataMap =eavAttrService.getAttrValuesByProdSetKey(getId(),getData().getEavSetKey());
		
		if(attrDataMap==null||attrDataMap.size()==0){
			attrDataMap=new HashMap<String,Object>();
		}
		//设置分类名称
		putCateNames(attrDataMap);
		//设置分类属性的值范围
		putRanges(attrDataMap,getData().getCateKey());
		//将结果设置回HomeEntityPo
		getData().setAttrDataMap(attrDataMap);
	}
	
	private void putCateNames(Map<String, Object> attrDataMap){
		List<String> ids = getAllCateIdsFromData();
		
		List<GlCatePo> cates=glCateQueryDao.findByIds(ids);
		for (GlCatePo cat : cates)
		{
			if(StringUtils.isNotBlank(cat.getName()))
				attrDataMap.put(cat.getName(), "");
		}
	}
	
	private List<String> getAllCateIdsFromData(){
		List<String> ids=new ArrayList<String>();
		if(StringUtils.isNotBlank(getData().getMainCateId()))
			ids.add(getData().getMainCateId());
		if(StringUtils.isNotBlank(getData().getStyleId()))
			ids.add(getData().getStyleId());
		if(StringUtils.isNotBlank(getData().getSubStyleId()))
			ids.add(getData().getSubStyleId());
		
		List<ProductMediaPo> medias=getData().getProductMediaPos();
		if(medias!=null){
		for (ProductMediaPo media : medias)
		{
			if(StringUtils.isNotBlank(media.getCateId())){
				ids.add(media.getCateId());
			}
		}
		}
		return ids;
	}
	/**
	 * solr getRange
	 * @param attrRangPo
	 * @return
	 */
	private void putRanges(Map<String,Object> map,String cat_key){		
		String area_range = eavAttrService.getAttrValuesByCateKeyAttr(cat_key, "area_range");
		String price_range = eavAttrService.getAttrValuesByCateKeyAttr(cat_key, "price_range");
		
		List<AttrRangPo> areas = AttrRangeUtil.getRangeJson(area_range);
		
		if(areas!=null){
			for (AttrRangPo attrRangPo : areas)
			{
				int attMin=ParseVal(attrRangPo.getAttrMin());
				int attMax=ParseVal(attrRangPo.getAttrMax());
				int area=ParseVal(getData().getArea());
				int Max_Value=(attMax==0)?Integer.MAX_VALUE:attMax;
				
				if (attMin <= area && Max_Value >= area){
					map.put(attMin + "-" + attMax,"");
					map.put(attMax + "-" + attMin,"");
				}
					
			}
		}

		List<AttrRangPo> prices = AttrRangeUtil.getRangeJson(price_range);
		
		if(prices!=null){
			for (AttrRangPo attrRangPo : prices)
			{
				int attMin=ParseVal(attrRangPo.getAttrMin());
				int attMax=ParseVal(attrRangPo.getAttrMax());
				int price=ParseVal(getData().getPrice());
				int Max_Value=(attMax==0)?Integer.MAX_VALUE:attMax;
				
				if (attMin <= price && Max_Value >= price){
					map.put(attMin + "-" + attMax,"");
					map.put(attMax + "-" + attMin,"");
				}
			}
		}
		
		//System.out.println("map:"+map+" cates:"+cates);
	}
	
	/**
	 * solr parse double
	 * @param d
	 * @return
	 */
	private int ParseVal(Double d){
		if(d==null){
			return 0;
		}else{
			return d.intValue();
		}
	}
	
	/**
	 * solr get home entity
	 * @param homeEntityPo
	 * @param productEntity
	 * @return
	 */
	private HomeEntityPo getHomeEntityPo(ProductEntity productEntity){
		Map<String,Object> attrMap=eavAttrService.getAttrValuesByProdSetKey(productEntity.getId(),getData().getEavSetKey());
		
		GlCatePo cate=glCateQueryDao.get(getData().getMainCateId());
		if(cate!=null){
			putRanges(attrMap,cate.getKey());
			getData().setCateKey(cate.getKey());
		}
		
		GlCatePo style =glCateQueryDao.get(getData().getStyleId());
		if(style!=null){
			putRanges(attrMap,style.getKey());
		}
		
		if(attrMap==null||attrMap.size()==0){
			attrMap=new HashMap<String,Object>();
		}
		
		//设置分类名称
		putCateNames(attrMap);
		
		getData().setAttrDataMap(attrMap);
		return getData();
	}	
	
}
